const path = require('path')

const REGEX = {
  EMAIL_RE: /^[a-z0-9\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+(?:\.[a-z0-9\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+)*@(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?$/
}
module.exports = (app) => {
  const start_time = Date.now()
  app.coreLogger.info('[egg-neko] starting...')

  const dir = path.join(app.config.baseDir, 'app/proto')
  app.loader.loadToApp(dir, 'proto')

  app.validator.addRule('jsonString', (rule, value) => {
    try {
      JSON.parse(value)
    } catch (err) {
      return 'must be json string'
    }
  })

  app.validator.addRule('strnum', (rule, value) => {
    let { TYPE_MAP } = app.validator.constructor || {}
    let { min, max } = rule || {}

    return TYPE_MAP['string'].call(app.validator, {format: /[0-9A-Za-z]+/, min, max}, value)
  })

  app.validator.addRule('username', (rule, value) => {
    // view Parameter's constructor @{APP_ROOT}/node_modules/parameter/index.js
    let error, {min = 6, max = 18} = rule || {}

    if (!REGEX.EMAIL_RE.test(value)) {
      error = `should be one email or valid username with length between ${min} and ${max}.`

      if (!/[0-9a-z]+/i.test(value)) {
        return error
      } else if (value.length < min || value.length > max) {
        return error
      } else {
        error = undefined
      }
    }

    return error
  })

  app.validator.addRule('student_no', (rule, value) => {
    return TYPE_MAP['strnum'].call(app.validator, {min: 6, max: 18}, value)
  })

  app.beforeStart(function* () {
    app.coreLogger.info('[egg-neko] started.')
    app.logger.info('start spent: %s ms', Date.now() - start_time)
  })
}
